package main

import (
	"context"
	"errors"
	"fmt"
	"github.com/mark3labs/mcp-go/mcp"
	"github.com/mark3labs/mcp-go/server"
	"os"
)

func main() {
	// 创建 MCP 服务器对象
	s := server.NewMCPServer("CalculatorServer", "1.0.0")

	// 添加计算器工具
	calculatorTool := mcp.NewTool("calculate",
		mcp.WithDescription("执行基本的算术运算"),
		mcp.WithString("operation",
			mcp.Required(),
			mcp.Description("要执行的算术运算类型"),
			mcp.Enum("add", "subtract", "multiply", "divide"),
		),
		mcp.WithNumber("x",
			mcp.Required(),
			mcp.Description("第一个数字"),
		),
		mcp.WithNumber("y",
			mcp.Required(),
			mcp.Description("第二个数字"),
		),
	)
	desc, _ := calculatorTool.MarshalJSON()
	fmt.Println(string(desc))

	s.AddTool(calculatorTool, func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
		fmt.Println("add tool calculator tool")
		op := request.Params.Arguments["operation"].(string)
		x := request.Params.Arguments["x"].(float64)
		y := request.Params.Arguments["y"].(float64)
		var result float64
		switch op {
		case "add":
			result = x + y
		case "subtract":
			result = x - y
		case "multiply":
			result = x * y
		case "divide":
			if y == 0 {
				return nil, errors.New("不允许除以零")
			}
			result = x / y
		default:
			return nil, fmt.Errorf("不支持的操作: %s", op)
		}
		return mcp.FormatNumberResult(result), nil
	})

	// 添加静态资源
	resource := mcp.NewResource("docs://readme", "项目说明文档",
		mcp.WithResourceDescription("项目的 README 文件"),
		mcp.WithMIMEType("text/markdown"),
	)
	s.AddResource(resource, func(ctx context.Context, request mcp.ReadResourceRequest) ([]mcp.ResourceContents, error) {
		content, err := os.ReadFile("README.md")
		if err != nil {
			return nil, err
		}
		return []mcp.ResourceContents{
			mcp.TextResourceContents{
				URI:      "docs://readme",
				MIMEType: "text/markdown",
				Text:     string(content),
			},
		}, nil
	})

	// 启动基于 stdio 的服务器
	//if err := server.ServeStdio(s); err != nil {
	//	log.Printf("Server error: %v\n", err)
	//}
	//
	server.NewSSEServer(s).Start("0.0.0.0:9700")
}
